package cn.itfcz.server.launch;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.itfcz.server.servlet.HttpFczServlet;
import cn.itfcz.server.socket.SocketProcess;

public class FczTomcat {

	public static final int port = 8888;
	public static final HashMap<String, HttpFczServlet> servletMapping = new HashMap<>();
	
	// 初始化，加载自定义servlet类
	public void init(){
		try {
			String basePath = FczTomcat.class.getResource("/").getPath();
			SAXReader reader = new SAXReader();
			Document document = reader.read(new File(basePath + "/web.xml"));
			Element root = document.getRootElement();
			List<Element> childElements = root.elements();
			for(Element element : childElements) {
				if("servlet".equals(element.getName())) {
					Element servletName = element.element("servlet-name");
					Element servletClass = element.element("servlet-class");
					System.out.println(servletName.getText()+"="+servletClass.getText());
					servletMapping.put(servletName.getText(), (HttpFczServlet)Class.forName(servletClass.getText()).newInstance());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	// 运行
	public void start() {
		try {
			ServerSocket serverSocket = new ServerSocket(port);
			System.out.println("fcz tomcat 1.0 server is started");
			while(!serverSocket.isClosed()) {
				Socket socket = serverSocket.accept();
				Thread thread = new SocketProcess(socket);
				thread.start();
			}
			System.out.println("socket is closed");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		FczTomcat tomcat = new FczTomcat();
		tomcat.init();
		tomcat.start();
		
	}
}
